package com.onetech.adrewards.free.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;

import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.listener.HttpIF;
import com.onetech.adrewards.free.objects.DeviceInfoDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;

public class ZuZuHttpRequest implements HttpIF{
	private static HttpIF _instance;
	private static final Lock createLock=new ReentrantLock();	
	public ZuZuHttpRequest(){
		
	}
	public static HttpIF getInstance(){
		if(_instance==null){
			createLock.lock();
			if(_instance==null){
				_instance=new ZuZuHttpRequest();
			}
			createLock.unlock();
		}
		return _instance;
	}
	@Override
	public APIRequestResult getDataFromServer(String url,Bundle params) {
		AdrewadsUtils.loadDeviceInfo();
		return getDataFromServer(url, AppConfig.deviceInfo);
	}
	@Override
	public APIRequestResult postDataToServer(String url,Bundle params){
		AdrewadsUtils.loadDeviceInfo();
		return postDataServer(url, AppConfig.deviceInfo,params);
	}
	private APIRequestResult postDataServer(String url,DeviceInfoDTO info,Bundle params){
		
		APIRequestResult result=null;		
		String data=postServer(url,info,params);
		if(data!=null && data.length()>0){
			try {
				JSONObject jb=new JSONObject(data);
				result=new APIRequestResult();
				result.error_code=jb.getString("err_code");
				result.error_msg=jb.getString("err_msg");
				//result.error_type=jb.getString("error_type");
				result.data=jb.get("data");
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
		return result;
	}	
	public static APIRequestResult getDataFromServer(String url,DeviceInfoDTO info){
		
		APIRequestResult result=null;
		
		String data=getStringFromURL(url,info);
		if(data!=null && data.length()>0){
			try {
				JSONObject jb=new JSONObject(data);
				result=new APIRequestResult();
				result.error_code=jb.getString("err_code");
				result.error_msg=jb.getString("err_msg");
				//result.error_type=jb.getString("error_type");
				result.data=jb.get("data");
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
		return result;
	}	
	public static String postServer(String url,DeviceInfoDTO info,Bundle params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);		
		httpPost.addHeader("x-device-id", info.getDevice_Id());
		httpPost.addHeader("x-device-type", info.getDevice_Type());
		httpPost.addHeader("x-imei", info.getImei());
		httpPost.addHeader("x-serial-number", info.getSerial_Number());
		httpPost.addHeader("x-app-id", info.getApp_Id());
		httpPost.addHeader("x-app-version", info.getApp_Version());
		httpPost.addHeader("x-hash-key", "");
		httpPost.addHeader("x-debug", "");
		httpPost.addHeader("x-token-id", "");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			List<String> listKey = new ArrayList<String>();

			for (String key : params.keySet()) {
				listKey.add(key);
			}
			for (String key : listKey) {
				String value = params.getString(key);
				nameValuePairs.add(new BasicNameValuePair(key, value));
			}						   
			UrlEncodedFormEntity form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
            httpPost.setEntity(form);            
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return builder.toString();
	}	
	
	public static String getStringFromURL(String url,DeviceInfoDTO info) {
		
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		
		HttpGet httpGet = new HttpGet(url);		
		httpGet.addHeader("x-device-id", info.getDevice_Id());
		httpGet.addHeader("x-device-type", info.getDevice_Type());
		httpGet.addHeader("x-imei", info.getImei());
		httpGet.addHeader("x-serial-number", info.getSerial_Number());
		httpGet.addHeader("x-app-id", info.getApp_Id());
		httpGet.addHeader("x-app-version", info.getApp_Version());
		httpGet.addHeader("x-hash-key", "");
		httpGet.addHeader("x-debug", "");
		//httpGet.addHeader("x-token_id", AppConfig.token);
		httpGet.addHeader("x-token-id", "");
		
		try {			
			
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return builder.toString();
	}
	public static String getStringAdRewardsXMLFromURL(String url) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);				
		
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content,"Shift_JIS"));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return builder.toString();
	}
}
